操作CSS

  1. 逐个设置

    $("div").css("width", "100px");
    $("div").css("height", "100px");
    $("div").css("background", "red");
  2. 链式设置
    注意点: 链式操作如果大于3步, 建议分开

$("div").css("width", "100px").css("height", "100px").css("background", "blue");
  1. 批量设置

    $("div").css({
        width: "100px",
        height: "100px",
        background: "red"
    });
  1. 获取CSS样式值
console.log($("div").css("background"));

操作位置和尺寸

  1. offset([coordinates])
    作用: 获取元素距离窗口的偏移位
//距离左窗口的大小
$(".son").offset().left
  1. position()
    作用: 获取元素距离定位元素的偏移位

    //相对于定位元素而言
    $(".son").position().left
  2. 设置位置和尺寸

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    // 设置元素的宽度
    $(".father").width("500px")

    $(".son").offset({
    left: 10
    });

    //注意点: position方法只能获取不能设置
    $(".son").position({
    left: 10
    });
    //但是可以设置css样式
    $(".son").css({
    left: "10px"
    });

scrollTop

  1. 获取
    获得滚动的偏移位

    1
    $(".scroll").scrollTop()

    为了保证浏览器的兼容, 获取网页滚动的偏移位不同

    1
    $("body").scrollTop()+$("html").scrollTop()
  2. 设置
    设置滚动的偏移位

    1
    $(".scroll").scrollTop(300);

    浏览器兼容同样存在

    1
    $("html,body").scrollTop(300);